//
//  CantripScriptManager.m
//  Cantrip
//
//  Created by James Callender on Thu Jul 22 2004.
//  Copyright (c) 2004 James Callender. All rights reserved.
//

#import "CantripScriptManager.h"


@implementation CantripScriptManager

- (id)init
{
    if (self = [super init]) {
		registeredPlugins = [[NSMutableDictionary alloc] init];
    }
    
    return self;
}

- (void)dealloc
{
    [registeredPlugins release];
    [super dealloc];
}

+ (CantripScriptManager *)sharedScriptManager
{
    static CantripScriptManager *manager;
    if(!manager) {
        manager = [[CantripScriptManager alloc] init];
		[manager registerPlugin:manager forScriptType:@"fscript"];
		[manager registerPlugin:manager forScriptType:@"applescript"];
    }
    return manager;
}

- (void)registerPlugin:(id)plugin forScriptType:(NSString *)type
{
    [registeredPlugins setObject:plugin forKey:type];
}

- (id)pluginRegisteredForType:(NSString *)type
{
    return [registeredPlugins objectForKey:type];
}

- (id)performScript:(NSString *)script ofType:(NSString *)type
{
    return [self performScript:script ofType:type withEnvironment:nil];
}

- (id)performScript:(NSString *)script ofType:(NSString *)type withEnvironment:(NSDictionary *)env
{
    id plugin, retv = nil;
    
    if (plugin = [registeredPlugins objectForKey:type]) {
		if ([plugin respondsToSelector:@selector(handleScript:ofType:withEnvironment:)]) {
			retv = [plugin handleScript:script ofType:type withEnvironment:env];
		} else {
			// log an error: plugin doesn't handle script protocol.  evil.
		}
    } else {
		// log an error: script type not supported
    }
    
    return retv;
}

- (id)handleScript:(NSString *)script ofType:(NSString *)type withEnvironment:(NSDictionary *)env
{
    if ([type isEqualToString:@"fscript"]) {
		if ([script respondsToSelector:@selector(asBlock)]) {
			id fscriptBlock = [script asBlock];
			id returnValue = [fscriptBlock value:[env objectForKey:@"worldController"]];
			return returnValue;
		} else {
			//Error, not supported
		}
    } else if ([type isEqualToString:@"applescript"]) {
		id ascript = [[NSAppleScript alloc] initWithSource:script];
		id result;
		NSDictionary *errorInfo;
		
		result = [ascript executeAndReturnError:&errorInfo]; 
		if (result == nil) {
			[[NSApp delegate] log:@"Applescript error: %@\n", 
				[errorInfo objectForKey:NSAppleScriptErrorBriefMessage]];
		}
		[ascript release];
    }
}

@end
